<?php

namespace app\sub\controller;

use think\Db;

class Order extends \Common
{

    # 获取税率
    public function GetTaxRate()
    {
        $aid = isset($this->token["pid"]) ? $this->token["pid"] : $this->token["id"];
        $tax = Db::name("tax")->where("aid", $aid)->find();
        if (empty($tax)) {
            $info = [
                "aid" => $aid
            ];
            Db::name("tax")->insert($info);
            $tax["tax"] = 0;
        }
        Code(200, false, (float)$tax["tax"] * 10000 / 1000000);
    }

    # 设置税率
    public function SetTaxRate()
    {
        $aid = isset($this->token["pid"]) ? $this->token["pid"] : $this->token["id"];
        if (isset($_POST["tax"])) {
            $tax = $_POST["tax"] * 100;
            $upInfo = [
                "tax" => $tax
            ];
            Db::name("tax")->where("aid", $aid)->update($upInfo);
            Code(200, "税率设置成功", $tax * 0.01);
        } else {
            Code(403, "服务器错误，请稍后再试");
        }
    }

    # 创建订单
    public function CreateOrder()
    {
        $aid = isset($this->token["pid"]) ? $this->token["pid"] : $this->token["id"];
        if (isset($_POST["type"]) && isset($_POST["ids"]) && isset($_POST["fee_rate"]) && isset($_POST["tax_rate"]) && isset($_POST["remark"]) && isset($_POST["bankname"]) && isset($_POST["bankcard"]) && isset($_POST["address"])) {
            $type = $_POST["type"];
            $ids = $_POST["ids"];
            $fee_rate = $_POST["fee_rate"];
            $tax_rate = $_POST["tax_rate"];
            $remark = $_POST["remark"];
            $bankname = $_POST["bankname"];
            $bankcard = $_POST["bankcard"];
            $address = $_POST["address"];
            $other_fee = $_POST["other_fee"];
            if ($type == "buy") {
                $gid_arr = explode(",", $ids);
                $good = Db::name("goods")->where("gid", "in", $gid_arr)->where("b_oid", 0)->select();
                $ub_id = 0;
                $up_id = 0;
                $AllPrive = 0;
                $lid = 0;
                foreach ($good as $value) {
                    if ($lid == 0) {
                        $lid = $value["lid"];
                    }
                    if ($value["ub_id"] != 0) {
                        if ($ub_id == 0) {
                            $ub_id = $value["ub_id"];
                        } else if ($ub_id != $value["ub_id"]) {
                            Code(403, "订单用户不同，无法结算");
                        }
                    } else if ($value["up_id"] != 0) {
                        if ($up_id == 0) {
                            $up_id = $value["up_id"];
                        } else if ($up_id != $value["up_id"]) {
                            Code(403, "订单用户不同，无法结算");
                        }
                    } else {
                        Code(403, "订单信息错误，无法结算");
                    }
                    $AllPrive = $value["final_price"] + ($value["final_price"] * $fee_rate) + ($value["final_price"] * $tax_rate);
                }
                $lot = Db::name("lot")->where("lid", $lid)->find();
                $order_number = "OB" . ($ub_id == 0 ? $up_id : $ub_id) . time();
                $order_info = [
                    "aid" => $aid,
                    "uid" => $ub_id == 0 ? $up_id : $ub_id,
                    "order_number" => $order_number,
                    "rate" => $lot["rate"],
                    "fee_rate" => $fee_rate * 100,
                    "tax" => $tax_rate * 100,
                    "bankname" => $bankname,
                    "bankcard" => $bankcard,
                    "address" => $address,
                    "belong" => $ub_id == 0 ? 3 : 1,
                    "price" => (float)$AllPrive + (float)$other_fee,
                    "status" => 0,
                    "create_time" => time(),
                    "remark" => $remark,
                    "other_fee" => $other_fee
                ];
                $addId = Db::name("order")->insertGetId($order_info);
                $update = [
                    "b_oid" => $addId
                ];
                foreach ($good as $value) {
                    Db::name("goods")->where("gid", $value["gid"])->update($update);
                }
                Code(200, "订单创建成功", $order_number);
            } else {
                if (isset($_POST["catafee"])) {
                    $catafee = $_POST["catafee"];
                    $gid_arr = explode(",", $ids);
                    $good = Db::name("goods")->where("gid", "in", $gid_arr)->where("s_oid", 0)->select();
                    $us_id = 0;
                    $AllPrive = 0;
                    $lid = 0;
                    foreach ($good as $value) {
                        if ($lid == 0) {
                            $lid = $value["lid"];
                        }
                        if ($value["us_id"] != 0) {
                            if ($us_id == 0) {
                                $us_id = $value["us_id"];
                            } else if ($us_id != $value["us_id"]) {
                                Code(403, "订单用户不同，无法结算");
                            }
                        } else {
                            Code(403, "订单信息错误，无法结算");
                        }
                        $AllPrive = $value["final_price"] + ($value["final_price"] * $fee_rate) + ($value["final_price"] * $tax_rate);
                    }
                    $lot = Db::name("lot")->where("lid", $lid)->find();
                    $order_number = "OS" . $us_id . time();
                    $order_info = [
                        "aid" => $aid,
                        "uid" => $us_id,
                        "order_number" => $order_number,
                        "rate" => $lot["rate"],
                        "fee_rate" => $fee_rate * 100,
                        "catafee" => $catafee,
                        "tax" => $tax_rate * 100,
                        "bankname" => $bankname,
                        "bankcard" => $bankcard,
                        "address" => $address,
                        "belong" => 2,
                        "price" => (float)$AllPrive + (float)$other_fee,
                        "status" => 0,
                        "create_time" => time(),
                        "remark" => $remark,
                        "other_fee" => $other_fee
                    ];
                    $addId = Db::name("order")->insertGetId($order_info);
                    $update = [
                        "s_oid" => $addId
                    ];
                    foreach ($good as $value) {
                        Db::name("goods")->where("gid", $value["gid"])->update($update);
                    }
                    Code(200, "订单创建成功", $order_number);
                } else {
                    Code(403, "服务器错误，请稍后再试");
                }
            }
        } else {
            Code(403, "服务器错误，请稍后再试");
        }
    }

    # 获取订单列表
    public function GetOrders()
    {
        $aid = isset($this->token["pid"]) ? $this->token["pid"] : $this->token["id"];
        if (isset($_GET["page"]) && isset($_GET["limit"]) && isset($_GET["type"]) && isset($_GET["search_key"])) {
            $type = $_GET["type"];
            $page = $_GET["page"];
            $limit = $_GET["limit"];
            $key = $_GET["search_key"];
            $where = [];
            $state = 0;
            $where[] = "(aid = {$aid})";
            if ($type == "buy") {
                $state = 1;
                if (isset($_GET["search_val"]) && $_GET["search_val"] != "") {
                    $value = $_GET["search_val"];
                    switch ($key) {
                        case "user_name" :
                            $uid = [];
                            $user = Db::name("user_buy")->where("name", $value)->field("ub_id")->select();
                            if (!empty($user)) {
                                foreach ($user as $val) {
                                    $uid[] = "uid = '{$val["ub_id"]}' and belong = 1";
                                }
                            }
                            $com = Db::name("user_proxy")->where("name", $value)->field("up_id")->select();
                            if (!empty($com)) {
                                foreach ($com as $val) {
                                    $uid[] = "uid = '{$val["up_id"]}' and belong = 3";
                                }
                            }
                            if (!empty($uid)) {
                                $where[] = "(" . join(" or ", $uid) . ")";
                            } else {
                                $where[] = "(belong = 100)";
                            }
                            break;
                        case "order_number" :
                            $where[] = "(order_number = '{$value}' and (belong = 1 or belong = 3))";
                    }
                } else {
                    $where[] = "belong = 3 or belong = 1";
                }
            } else {
                $state = 2;
                $where[] = "(belong = 2)";
                if (isset($_GET["search_val"]) && $_GET["search_val"] != "") {
                    $value = $_GET["search_val"];
                    switch ($key) {
                        case "user_name" :
                            $uid = [];
                            $user = Db::name("user_send")->where("name", $value)->field("us_id")->select();
                            if (!empty($user)) {
                                foreach ($user as $val) {
                                    $uid[] = "uid = '{$val["us_id"]}'";
                                }
                            }
                            if (!empty($uid)) {
                                $where[] = "(" . join(" or ", $uid) . ")";
                            } else {
                                $where[] = "(belong = 100)";
                            }
                            break;
                        case "order_number" :
                            $where[] = "(order_number = '{$value}')";
                    }
                }
            }
            $whereWord = join(" and ", $where);
            if ($whereWord == "") {
                $order = Db::name("order")->orderRaw("field(status, 0, 1, -1), create_time desc")->page($page, $limit)->select();
                $count = Db::name("order")->count();
            } else {
                $order = Db::name("order")->where($whereWord)->orderRaw("field(status, 0, 1, -1), create_time desc")->page($page, $limit)->select();
                $count = Db::name("order")->where($whereWord)->count();
            }

            $list = [];
            $lotInfo = [];
            if (!empty($order)) {
                foreach ($order as $value) {
                    $goods = [];
                    $AllPrice = 0;
                    if ($state == 1) {
                        $good = Db::name("goods")->where("b_oid", $value["oid"])->select();
                        foreach ($good as $val) {
                            if ($val['lid'] == 35) {
                                $lotInfo = Db::name("lot")->where("lid", $val["lid"])->find();
                                $fee = (float)$val["final_price"] * ((float)$value["fee_rate"] * 10000 / 1000000);
                                $tax = $fee * ((float)$value["tax"] * 10000 / 1000000);
                                $sum = (float)$val["final_price"] + (float)$fee + (float)$tax + (float)$val["postage"];
                                $AllPrice += $sum;
                                $goods[] = [
                                    "id" => (int)$val["gid"],
                                    "fee" => $fee,
                                    "fee_rate" => (float)$value["fee_rate"] * 10000 / 1000000,
                                    "final_price" => $val["final_price"],
                                    "name" => $val["name"],
                                    "number" => $val["number"] . '-' . $val['location'],
                                    "sum" => $sum,
                                    "tax" => $tax,
                                    "tax_rate" => $value["tax"] * 10000 / 1000000,
                                    "postage" => $val["postage"]
                                ];
                            }
                        }
                    } else {
                        $good = Db::name("goods")->where("s_oid", $value["oid"])->select();
                        foreach ($good as $val) {
                            if ($val['lid'] == 35) {
                                $lotInfo = Db::name("lot")->where("lid", $val["lid"])->find();
                                $fee = (float)$val["final_price"] * ((float)$value["fee_rate"] * 10000 / 1000000);
                                $tax = $fee * ((float)$value["tax"] * 10000 / 1000000);
                                $sum = (float)$val["final_price"] - (float)$fee - (float)$tax - (float)$value["catafee"] * 10000 / 1000000 + (float)$val["postage"];
                                $AllPrice += $sum;
                                $goods[] = [
                                    "id" => (int)$val["gid"],
                                    "catafee" => (float)$value["catafee"] * 10000 / 1000000,
                                    "fee" => $fee,
                                    "fee_rate" => (float)$value["fee_rate"] * 10000 / 1000000,
                                    "final_price" => $val["final_price"],
                                    "name" => $val["name"],
                                    "number" => $val["number"] . '-' . $val['location'],
                                    "sum" => $sum,
                                    "tax" => $tax,
                                    "tax_rate" => $value["tax"] * 10000 / 1000000,
                                    "postage" => $val["postage"]
                                ];
                            }
                        }
                    }
                    switch ($value["belong"]) {
                        case 1 :
                            $user = Db::name("user_buy")->where("ub_id", $value["uid"])->find();
                            $number = Db::name("num")->where("aid", $value["aid"])->where("ub_id", $value["uid"])->find();
                            break;
                        case 2 :
                            $user = Db::name("user_send")->where("us_id", $value["uid"])->find();
                            $number = Db::name("user_send_company")->where("us_id", $value["uid"])->find();
                            break;
                        case 3 :
                            $user = Db::name("user_proxy")->where("up_id", $value["uid"])->find();
                            $number = ["number" => "代拍公司"];
                            break;
                        default :
                            $user = ["name" => ""];
                    }

                    $list[] = [
                        "id" => $value["oid"],
                        "lotId" => isset($lotInfo['lid']) ? $lotInfo['lid'] : '',
                        "lotName" => isset($lotInfo['name']) ? $lotInfo['name'] : '',
                        "address" => $value["address"],
                        "bankname" => $value["bankname"],
                        "bankcard" => $value["bankcard"],
                        "create_time" => date("Y-m-d", $value["create_time"]),
                        "order_number" => $value["order_number"],
                        "price" => (float)$AllPrice - (float)$value["other_fee"],
                        "status" => (int)$value["status"],
                        "type" => $state == 1 ? "buy" : "send",
                        "user_name" => empty($user) ? "-" : $user["name"],
                        "user_num" => empty($number) ? "-" : $number["number"],
                        "remark" => $value["remark"],
                        "goods" => $goods,
                        "other_fee" => (float)$value["other_fee"],
                        "lot_rate" => $value["rate"],
                        "price_rmb" => $state == 1 ? ((float)$AllPrice + (float)$value["other_fee"]) * (float)$value["rate"] : ((float)$AllPrice - (float)$value["other_fee"]) * (float)$value["rate"]
                    ];
                }
            }

            Code(200, false, ["list" => $list, "total" => $count]);

        } else {
            Code(403, "服务器错误，请稍后再试");
        }
    }

    public function UpdateOrder()
    {
        if (isset($_POST["bankname"]) && isset($_POST["bankcard"]) && isset($_POST["address"]) && isset($_POST["remark"]) && isset($_POST["id"]) && isset($_POST["status"])) {
            $status = $_POST["status"];
            $bankname = $_POST["bankname"];
            $bankcard = $_POST["bankcard"];
            $address = $_POST["address"];
            $remark = $_POST["remark"];
            $other_fee = $_POST["other_fee"];
            $oid = $_POST["id"];
            $upInfo = [
                "address" => $address,
                "bankname" => $bankname,
                "bankcard" => $bankcard,
                "status" => $status,
                "remark" => $remark,
                "other_fee" => $other_fee
            ];
            $order = Db::name("order")->where("oid", $oid)->find();
            if ($order["status"] == $status) {
                $msg = "订单更新成功";
            } else {
                switch ($status) {
                    case 1:
                        $msg = "付款成功";
                        if ($order["belong"] == 2) {
                            $good = Db::name("goods")->where("s_oid", $oid)->select();
                            foreach ($good as $value) {
                                if ($value["state"] == 5 || $value["state"] == 6) {
                                    $info = [
                                        "state" => 7,
                                        "is_end" => 1
                                    ];
                                } else {
                                    $info = [
                                        "is_end" => 1
                                    ];
                                }
                                Db::name("goods")->where("s_oid", $oid)->update($info);
                            }
                        } else {
                            $info = ["state" => 4];
                            Db::name("goods")->where("b_oid", $oid)->update($info);
                        };
                        break;
                    case -1:
                        $msg = "作废成功";
                        if ($order["belong"] == 2) {
                            $info = ["s_oid" => 0];
                            Db::name("goods")->where("s_oid", $oid)->update($info);
                        } else {
                            $info = ["b_oid" => 0];
                            Db::name("goods")->where("b_oid", $oid)->update($info);
                        };
                        break;
                }
            }
            Db::name("order")->where("oid", $oid)->update($upInfo);
            Code(200, $msg);
        } else {
            Code(403, "服务器错误，请稍后再试");
        }
    }

}